Page({
  data: {
    jobs: [],
    filteredJobs: [],
    status: 'open',
    keyword: '',
    skills: '',
    loading: false,
    baseUrl: 'http://localhost:3000',
    userInfo: null,
    userInfoLoaded: false
  },

  onLoad: function() {
    console.log('Jobs page loaded');
    this.loadUserInfo().then(() => {
      console.log('User info loaded, loading jobs');
      this.loadJobs();
    }).catch((error) => {
      console.error('Error loading user info:', error);
      wx.showToast({
        title: '加载用户信息失败',
        icon: 'none'
      });
    });

    // 监听来自其他页面的事件
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('reloadJobs', () => {
      console.log('Received reloadJobs event, reloading jobs');
      this.loadJobs();
    });
  },

  onShow: function() {
    console.log('Jobs page shown');
    this.loadUserInfo().then(() => {
      console.log('User info reloaded, reloading jobs');
      this.loadJobs();
    }).catch((error) => {
      console.error('Error reloading user info:', error);
      wx.showToast({
        title: '加载用户信息失败',
        icon: 'none'
      });
    });
  },

  loadUserInfo: function() {
    return new Promise((resolve, reject) => {
      const userInfo = wx.getStorageSync('userInfo');
      console.log('Retrieved user info:', userInfo);
      if (userInfo) {
        this.setData({ userInfo, userInfoLoaded: true }, () => {
          console.log('User info set to state:', this.data.userInfo);
          resolve();
        });
      } else {
        console.log('No user info found, redirecting to login');
        wx.redirectTo({
          url: '/pages/login/login'
        });
        reject(new Error('User info not found'));
      }
    });
  },

  loadJobs: function() {
    const { userInfo, status, keyword, skills } = this.data;

    let requestData = {
      status,
      keyword,
      skills
    };

    if (userInfo && userInfo.role === 'company') {
      requestData.userId = userInfo.id;
      requestData.role = 'company';
    } else if (userInfo && (userInfo.role === 'student' || userInfo.role === 'alumni')) {
      requestData.role = 'student'; // or 'alumni', based on your requirement
    }

    console.log('Loading jobs with params:', requestData);

    this.setData({ loading: true });
    wx.request({
      url: `${this.data.baseUrl}/api/jobs`,
      method: 'GET',
      data: requestData,
      success: (res) => {
        console.log('Jobs loaded successfully:', res.data);
        this.setData({
          jobs: res.data,
          loading: false
        }, () => {
          this.updateFilteredJobs();
        });
      },
      fail: (err) => {
        console.error('获取岗位列表失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none',
          duration: 2000
        });
        this.setData({ loading: false });
      }
    });
  },

  getFilteredJobs: function() {
    const { jobs, status, keyword, skills, userInfo } = this.data;

    // 如果是普通用户，只显示开放中的岗位
    if (userInfo.role !== 'company') {
      return jobs.filter(job => job.status === 'open');
    }

    return jobs.filter(job => {
      const matchesStatus = job.status === status;
      const matchesKeyword = !keyword || job.title.includes(keyword);
      const matchesSkills = !skills || job.skills.includes(skills);
      return matchesStatus && matchesKeyword && matchesSkills;
    });
  },

  updateFilteredJobs: function() {
    const filteredJobs = this.getFilteredJobs();
    this.setData({ filteredJobs });
  },

  toggleJobStatus: function(e) {
    const { id, status: currentStatus } = e.currentTarget.dataset;
    const newStatus = currentStatus === 'open' ? 'closed' : 'open';

    wx.showModal({
      title: '确认操作',
      content: `确定要将该岗位${newStatus === 'open' ? '开放' : '关闭'}吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '更新中...'
          });

          wx.request({
            url: `${this.data.baseUrl}/api/jobs/${id}`,
            method: 'PUT',
            data: {
              status: newStatus
            },
            success: (res) => {
              wx.hideLoading();
              if (res.data.success) {
                wx.showToast({
                  title: '更新成功',
                  icon: 'success'
                });

                // 更新本地的jobs数组
                const updatedJobs = this.data.jobs.map(job => {
                  if (job.id === id) {
                    return { ...job, status: newStatus };
                  }
                  return job;
                });

                this.setData({ jobs: updatedJobs }, () => {
                  this.updateFilteredJobs();
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '更新失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  searchJobs: function(e) {
    this.setData({
      keyword: e.detail.value
    }, () => {
      this.updateFilteredJobs();
    });
  },

  filterBySkills: function(e) {
    this.setData({
      skills: e.detail.value
    }, () => {
      this.updateFilteredJobs();
    });
  },

  handleJobAction: function(e) {
    const { id, status } = e.currentTarget.dataset;
    const { role } = this.data.userInfo;

    if (role === 'company') {
      this.toggleJobStatus(e);
    } else if (role === 'student' || role === 'alumni') {
      this.viewJobDetail(e);
    }
  },

  viewJobDetail: function(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/job-detail/job-detail?id=${id}`
    });
  },

  switchStatus: function(e) {
    const newStatus = e.currentTarget.dataset.status;
    this.setData({
      status: newStatus
    }, () => {
      this.updateFilteredJobs();
    });
  }
});